package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    /**
     * 查询自媒体文章
     *
     * @param dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //todo 1.检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //todo 2.分页查询 条件查询
        IPage page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //todo 2.1 状态
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //todo 2.2 时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //todo 2.3 所属频道ID
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        if (StringUtils.isNoneBlank(dto.getKeyword())) {
            //todo 2.4 关键字模糊查询
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }


        //todo 2.5 查询当前用户登录的文章
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());

        //todo 2.6 根据时间倒序排序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        IPage iPage = baseMapper.selectPage(page, lambdaQueryWrapper);

        //todo 3.封装返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(), (int) iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        return responseResult;
    }
}
